<template>
  <div class="app-container">
    <el-card>
      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="search-form">
        <el-form-item label="消息标题" prop="title">
          <el-input v-model="queryParams.title" placeholder="请输入消息标题" clearable style="width: 240px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="消息类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择消息类型" clearable style="width: 240px">
            <el-option v-for="dict in typeOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="阅读状态" prop="readStatus">
          <el-select v-model="queryParams.readStatus" placeholder="请选择阅读状态" clearable style="width: 240px">
            <el-option v-for="dict in readStatusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <el-row :gutter="10" class="mb-3">
        <el-col :span="1.5">
          <el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" :icon="Check" :disabled="selectedIds.length === 0" @click="handleBatchRead">标为已读</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" :icon="Check" @click="handleAllRead">全部已读</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" :icon="Delete" :disabled="selectedIds.length === 0" @click="handleBatchDelete">批量删除</el-button>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <el-table v-loading="loading" :data="messageList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="消息ID" prop="id" width="80" />
        <el-table-column label="消息标题" prop="title" :show-overflow-tooltip="true" />
        <el-table-column label="消息类型" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getTagType(scope.row.type)">{{ getTypeLabel(scope.row.type) }}</el-tag>
        </template>
      </el-table-column>
        <el-table-column label="阅读状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.readStatus === 0 ? 'danger' : 'success'">
              {{ scope.row.readStatus === 0 ? '未读' : '已读' }}
          </el-tag>
        </template>
      </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createdAt" width="160">
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.createdAt) }}</span>
        </template>
      </el-table-column>
        <el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="primary" link :icon="View" @click="handleView(scope.row)">查看</el-button>
          <el-button
              v-if="scope.row.readStatus === 0" 
              type="success" 
              link 
              :icon="Check" 
              @click="handleRead(scope.row)"
            >
              已读
          </el-button>
            <el-button type="danger" link :icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

      <!-- 分页 -->
    <pagination
        v-if="total > 0"
      :total="total"
        v-model:page="queryParams.page"
        v-model:limit="queryParams.limit"
      @pagination="getList"
    />
    </el-card>

    <!-- 添加消息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="700px" append-to-body>
      <el-form ref="messageFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="消息标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入消息标题" />
        </el-form-item>
        <el-form-item label="消息类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择消息类型" style="width: 100%">
            <el-option v-for="dict in typeOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="消息内容" prop="content">
          <el-input v-model="form.content" type="textarea" placeholder="请输入消息内容" :rows="5" />
        </el-form-item>
        <el-form-item label="接收者类型" prop="receiverType">
          <el-radio-group v-model="form.receiverType">
            <el-radio :label="1">全部用户</el-radio>
            <el-radio :label="2">指定用户</el-radio>
            <el-radio :label="3">指定部门</el-radio>
            <el-radio :label="4">指定角色</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="接收者" prop="receiverIds" v-if="form.receiverType > 1">
          <el-select
            v-model="form.receiverIds" 
            multiple 
            placeholder="请选择接收者"
            style="width: 100%"
            :loading="receiverLoading"
          >
            <el-option
              v-for="item in receiverOptions" 
              :key="item.id"
              :label="item.name || item.username || item.title" 
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
      </div>
      </template>
    </el-dialog>

    <!-- 消息详情对话框 -->
    <el-dialog title="消息详情" v-model="detailDialog.visible" width="600px" append-to-body>
      <div class="message-detail">
        <div class="detail-header">
          <div class="detail-title">{{ detailDialog.message.title }}</div>
          <div class="detail-info">
            <el-tag :type="getTagType(detailDialog.message.type)">
              {{ getTypeLabel(detailDialog.message.type) }}
            </el-tag>
            <span class="detail-time">{{ formatDateTime(detailDialog.message.createdAt) }}</span>
          </div>
        </div>
        <div class="detail-content">
          {{ detailDialog.message.content }}
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="detailDialog.visible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { Search, Refresh, Plus, Check, Delete, View } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getMessageList, 
  getMessageDetail, 
  createMessage, 
  deleteMessage, 
  batchDeleteMessages, 
  markMessageRead,
  markAllMessagesRead
} from '@/api/message'
import Pagination from '@/components/Pagination/index.vue'
import { getUserList } from '@/api/user'
import { getDeptTree } from '@/api/dept'
import { getRoleList } from '@/api/role'

// 状态数据字典
const typeOptions = [
  { value: 1, label: '系统通知', type: 'primary' },
  { value: 2, label: '任务提醒', type: 'success' },
  { value: 3, label: '其他', type: 'warning' }
]

const readStatusOptions = [
  { value: 0, label: '未读' },
  { value: 1, label: '已读' }
]

// 查询参数
const queryParams = reactive({
        page: 1,
        limit: 10,
  title: '',
  type: null,
  readStatus: null
})

// 日期范围
const dateRange = ref([])

// 表格数据
const messageList = ref([])
const loading = ref(false)
const total = ref(0)
const selectedIds = ref([])
const queryFormRef = ref(null)
const messageFormRef = ref(null)

// 表单参数
const form = reactive({
  title: '',
  content: '',
  type: 1,
  receiverType: 1,
  receiverIds: []
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '消息标题不能为空', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '消息类型不能为空', trigger: 'change' }
  ],
  content: [
    { required: true, message: '消息内容不能为空', trigger: 'blur' }
  ],
  receiverType: [
    { required: true, message: '接收者类型不能为空', trigger: 'change' }
  ],
  receiverIds: [
    { 
      required: true, 
      message: '接收者不能为空', 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (form.receiverType > 1 && (!value || value.length === 0)) {
          callback(new Error('请选择接收者'))
        } else {
          callback()
        }
      }
    }
  ]
}

// 弹窗对象
const dialog = reactive({
  title: '发送消息',
  visible: false
})

// 详情对话框
const detailDialog = reactive({
  visible: false,
  message: {}
})

// 接收者数据
const receiverOptions = ref([])
const receiverLoading = ref(false)

// 格式化日期时间
const formatDateTime = (value) => {
  if (!value) return ''
  return new Date(value).toLocaleString()
}

// 获取标签类型
const getTagType = (type) => {
  const option = typeOptions.find(opt => opt.value === type)
  return option ? option.type : 'info'
}

// 获取类型标签
const getTypeLabel = (type) => {
  const option = typeOptions.find(opt => opt.value === type)
  return option ? option.label : '未知'
}

// 获取消息列表
const getList = async () => {
  loading.value = true
  try {
    // 处理日期范围
    const params = { ...queryParams }
    if (dateRange.value && dateRange.value.length === 2) {
      params.beginTime = dateRange.value[0]
      params.endTime = dateRange.value[1]
    }
    
    const res = await getMessageList(params)
    messageList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取消息列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载接收者数据
const loadReceivers = async () => {
  if (form.receiverType <= 1) return
  
  receiverLoading.value = true
  try {
    let res
    if (form.receiverType === 2) {
      // 加载用户列表
      res = await getUserList({ limit: 100 })
      receiverOptions.value = res.data.list
    } else if (form.receiverType === 3) {
      // 加载部门列表
      res = await getDeptTree()
      receiverOptions.value = flattenTree(res.data)
    } else if (form.receiverType === 4) {
      // 加载角色列表
      res = await getRoleList({ limit: 100 })
      receiverOptions.value = res.data.list
    }
  } catch (error) {
    console.error('获取接收者列表失败:', error)
  } finally {
    receiverLoading.value = false
  }
}

// 展平树形结构
const flattenTree = (tree) => {
  const result = []
  
  const flatten = (items) => {
    items.forEach(item => {
      result.push(item)
      if (item.children && item.children.length > 0) {
        flatten(item.children)
      }
    })
  }
  
  flatten(tree)
  return result
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  dateRange.value = []
  queryFormRef.value.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 查看消息
const handleView = async (row) => {
  detailDialog.message = { ...row }
  detailDialog.visible = true
  
  // 如果是未读消息，标记为已读
  if (row.readStatus === 0) {
    try {
      await markMessageRead(row.id)
      row.readStatus = 1
    } catch (error) {
      console.error('标记消息已读失败:', error)
    }
  }
}

// 标记消息为已读
const handleRead = async (row) => {
  try {
    await markMessageRead(row.id)
    ElMessage.success('消息已标记为已读')
    row.readStatus = 1
  } catch (error) {
    console.error('标记消息已读失败:', error)
    ElMessage.error('操作失败')
  }
}

// 批量标记为已读
const handleBatchRead = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  try {
    await Promise.all(selectedIds.value.map(id => markMessageRead(id)))
    ElMessage.success('批量标记已读成功')
    getList()
  } catch (error) {
    console.error('批量标记已读失败:', error)
    ElMessage.error('操作失败')
  }
}

// 全部标记为已读
const handleAllRead = async () => {
  ElMessageBox.confirm('确认将全部消息标记为已读吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await markAllMessagesRead()
      ElMessage.success('操作成功')
      getList()
    } catch (error) {
      console.error('标记全部已读失败:', error)
      ElMessage.error('操作失败')
    }
  })
}

// 删除按钮操作
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除该消息吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteMessage(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 批量删除操作
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  ElMessageBox.confirm('确认删除选中的消息吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
  }).then(async () => {
    try {
      await batchDeleteMessages(selectedIds.value)
      ElMessage.success('批量删除成功')
      getList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  })
}

// 表单重置
const resetForm = () => {
  messageFormRef.value?.resetFields()
  Object.assign(form, {
    title: '',
    content: '',
    type: 1,
    receiverType: 1,
    receiverIds: []
  })
}

// 新增按钮操作
const handleAdd = () => {
  resetForm()
  dialog.visible = true
}

// 监听接收者类型变化
const watchReceiverType = (val) => {
  if (val > 1) {
    loadReceivers()
  }
  form.receiverIds = []
}

// 提交表单
const submitForm = () => {
  messageFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        await createMessage(form)
        ElMessage.success('发送成功')
        dialog.visible = false
        getList()
      } catch (error) {
        console.error('发送失败:', error)
        ElMessage.error('发送失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 监听接收者类型变化
watch(() => form.receiverType, watchReceiverType)

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.mb-3 {
  margin-bottom: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.message-detail {
  .detail-header {
    margin-bottom: 20px;
    
    .detail-title {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 10px;
    }
    
    .detail-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .detail-time {
        color: #909399;
    font-size: 14px;
      }
    }
  }

  .detail-content {
    padding: 20px;
    background-color: #f5f7fa;
    border-radius: 4px;
    min-height: 150px;
    white-space: pre-wrap;
  }
}
</style> 